package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import admin.forms.ApplicationTemplateForm;
import admin.models.ApplicationTemplateModel;
import entities.ApplicationTemplate;

@SuppressWarnings("serial")
public class ApplicationTemplateEditServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/apptemplate/list");
			return ;
		}
		
		ApplicationTemplateModel appTemplateModel = ApplicationTemplateModel.getInstance();
		ApplicationTemplate appTemplate = appTemplateModel.get(id);
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("template", appTemplate);
		try {
			request.getRequestDispatcher("/admin/pages/application_template_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/apptemplate/list");
			return ;
		}
		
		request.setAttribute("appId", id);
		
		ApplicationTemplateModel appTemplateModel = ApplicationTemplateModel.getInstance();
		ApplicationTemplate appTemplate = appTemplateModel.get(id);
		
		TreeMap<String, Object> form = ApplicationTemplateForm.checkEditValid(request, appTemplate);
		appTemplate = (ApplicationTemplate) form.get("template");
		check = (TreeMap<String, String>) form.get("checkValid");
		
		if (check.size() == 0) {
			appTemplateModel.insert(appTemplate);
			
			request.setAttribute("success", "Update template " + appTemplate.getId() + " success");
		}
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("template", appTemplate);
		try {
			request.getRequestDispatcher("/admin/pages/application_template_form.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
